package com.mswork.mes.service.impl;

import java.util.*;

import com.mswork.common.core.domain.AjaxResult;
import com.mswork.common.core.domain.model.LoginUser;
import com.mswork.common.utils.DateUtils;
import com.mswork.common.utils.SecurityUtils;
import com.mswork.mes.domain.*;
import com.mswork.mes.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.mswork.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.mswork.mes.service.IStoreOrderService;

/**
 * 工单管理Service业务层处理
 *
 * @author ylq
 * @date 2025-03-05
 */
@Service
@Slf4j
public class StoreOrderServiceImpl implements IStoreOrderService {

    @Autowired
    private StoreOrderMapper storeOrderMapper;
    @Autowired
    private StoreOrderCargoMapper storeOrderCargoMapper;
    @Autowired
    private StoreOrderAuxiliaryMapper storeOrderAuxiliaryMapper;
    @Autowired
    private ProjectCargoMapper projectCargoMapper;
    @Autowired
    private ProjectExtendMapper projectExtendMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ImagesMapper imagesMapper;
    @Autowired
    private AuxiliaryMapper auxiliaryMapper;
    @Autowired
    private UserMapper userMapper;

    /** 查询工单管理 */
    @Override
    public StoreOrder selectStoreOrderByOrderId(Long orderId) {
        return storeOrderMapper.selectStoreOrderByOrderId(orderId);
    }

    /** 查询工单管理列表 */
    @Override
    public List<StoreOrder> selectStoreOrderList(StoreOrder storeOrder) {
        return storeOrderMapper.selectStoreOrderList(storeOrder);
    }

    /** 新增工单管理 */
    @Transactional
    @Override
    public AjaxResult insertStoreOrder(StoreOrder storeOrder) {
        if(storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 2L){
            return insertOrderByCargo(storeOrder);
        }else if(storeOrder.getOrderType() == 3L || storeOrder.getOrderType() == 4L){
            return insertOrderByAuxiliary(storeOrder);
        }
        return AjaxResult.error("工单类型错误");
    }

    public AjaxResult insertOrderByCargo(StoreOrder storeOrder) {
        try {
            //校验及修改项目工单货物未入库数量
            ProjectCargo projectCargo = new ProjectCargo();
            projectCargo.setProjectId(storeOrder.getProjectId().intValue());
            List<ProjectCargo> projectCargoList = projectCargoMapper.selectProjectCargoList(projectCargo);
            if (storeOrder.getOrderType() == 1L) {
                Map<String, Integer> projectCargoMap = projectCargoList.stream().collect(Collectors.toMap(ProjectCargo::getCargoName, ProjectCargo::getCargoInputNum));
                List<StoreOrderCargo> storeOrderCargoList = storeOrder.getStoreOrderCargoList();
                List<String> diffList = storeOrderCargoList.stream().filter(d -> {
                    Integer cargoInputNum = projectCargoMap.get(d.getCargoName());
                    d.setCargoInputNum(cargoInputNum.longValue());
                    return d.getCargoNum() != null && d.getCargoNum().intValue() > cargoInputNum;
                }).map(StoreOrderCargo::getCargoName).collect(Collectors.toList());
                if (diffList != null && diffList.size() > 0) {
                    return AjaxResult.error("未入库数量已变更，请刷新页面");
                }
                storeOrderCargoList.stream().filter(f -> f.getCargoNum() != null && f.getCargoNum() > 0).forEach(d -> {
                    projectCargo.setCargoName(d.getCargoName());
                    projectCargo.setCargoInputNum(d.getCargoInputNum().intValue() - d.getCargoNum().intValue());
                    projectExtendMapper.updateInputNum(projectCargo);
                });
            } else if (storeOrder.getOrderType() == 2L) {
                Map<String, Integer> projectCargoMap = projectCargoList.stream().collect(Collectors.toMap(ProjectCargo::getCargoName, ProjectCargo::getCargoOutNum));
                List<StoreOrderCargo> storeOrderCargoList = storeOrder.getStoreOrderCargoList();
                List<String> diffList = storeOrderCargoList.stream().filter(d -> {
                    Integer cargoOutNum = projectCargoMap.get(d.getCargoName());
                    d.setCargoOutNum(cargoOutNum.longValue());
                    return d.getCargoNum() != null && d.getCargoNum().intValue() > cargoOutNum;
                }).map(StoreOrderCargo::getCargoName).collect(Collectors.toList());
                if (diffList != null && diffList.size() > 0) {
                    return AjaxResult.error("未出库数量已变更，请刷新页面");
                }
                storeOrderCargoList.stream().filter(f -> f.getCargoNum() != null && f.getCargoNum() > 0).forEach(d -> {
                    projectCargo.setCargoName(d.getCargoName());
                    projectCargo.setCargoOutNum(d.getCargoOutNum().intValue() - d.getCargoNum().intValue());
                    projectExtendMapper.updateOutNum(projectCargo);
                });
            }
            //插入工单数据
            storeOrder.setCreateTime(DateUtils.getNowDate());
            storeOrder.setUpdateTime(DateUtils.getNowDate());
            storeOrder.setOrderBatch(System.currentTimeMillis());
            storeOrder.setOrderStatus("0");
            storeOrderMapper.insertStoreOrder(storeOrder);
            //插入工单货物数据
            insertStoreOrderCargo(storeOrder);
        } catch (Exception e) {
            log.error("新建工单失败|{}", e);
            throw new RuntimeException("新建工单失败", e);
        }
        return AjaxResult.success();
    }

    /** 新增工单货物信息 */
    public void insertStoreOrderCargo(StoreOrder storeOrder) {
        List<StoreOrderCargo> storeOrderCargoList = storeOrder.getStoreOrderCargoList();
        Long orderId = storeOrder.getOrderId();
        if (StringUtils.isNotNull(storeOrderCargoList)) {
            List<StoreOrderCargo> list = new ArrayList<StoreOrderCargo>();
            for (StoreOrderCargo storeOrderCargo : storeOrderCargoList) {
                storeOrderCargo.setCargoId(null);
                storeOrderCargo.setCargoNum(storeOrderCargo.getCargoNum() == null ? 0 : storeOrderCargo.getCargoNum());
                storeOrderCargo.setOrderId(orderId);
                storeOrderCargo.setCreateTime(new Date());
                storeOrderCargo.setUpdateTime(new Date());
                storeOrderCargo.setStatus("1");
                list.add(storeOrderCargo);
            }
            if (list.size() > 0) {
                storeOrderCargoMapper.batchStoreOrderCargo(list);
            }
        }
    }
    public AjaxResult insertOrderByAuxiliary(StoreOrder storeOrder) {
        try {
            //插入工单数据
            storeOrder.setCreateTime(DateUtils.getNowDate());
            storeOrder.setUpdateTime(DateUtils.getNowDate());
            storeOrder.setOrderBatch(System.currentTimeMillis());
            storeOrder.setOrderStatus("0");
            storeOrderMapper.insertStoreOrder(storeOrder);
            //插入工单货物数据
            insertStoreOrderAuxiliary(storeOrder);
            if(storeOrder.getOrderType() == 4L){
                uploadStoreOrderAuxiliary(storeOrder);
            }
        } catch (Exception e) {
            log.error("新建工单失败|{}", e);
            throw new RuntimeException("新建工单失败", e);
        }
        return AjaxResult.success();
    }

    /** 新增辅料工单表信息 */
    public void insertStoreOrderAuxiliary(StoreOrder storeOrder) {
        List<StoreOrderAuxiliary> storeOrderAuxiliaryList = storeOrder.getStoreOrderAuxiliaryList();
        Long orderId = storeOrder.getOrderId();
        if (StringUtils.isNotNull(storeOrderAuxiliaryList)) {
            List<StoreOrderAuxiliary> list = new ArrayList<StoreOrderAuxiliary>();
            for (StoreOrderAuxiliary storeOrderAuxiliary : storeOrderAuxiliaryList) {
                storeOrderAuxiliary.setAuxiliaryId(null);
                storeOrderAuxiliary.setOrderId(orderId);
                storeOrderAuxiliary.setCreateTime(new Date());
                storeOrderAuxiliary.setUpdateTime(new Date());
                storeOrderAuxiliary.setStatus("1");
                list.add(storeOrderAuxiliary);
            }
            if (list.size() > 0) {
                storeOrderAuxiliaryMapper.batchStoreOrderAuxiliary(list);
            }
        }
    }

    /** 出库更新清单数据 */
    public void uploadStoreOrderAuxiliary(StoreOrder storeOrder){
        storeOrder.getStoreOrderAuxiliaryList().stream().forEach(d -> {
            Auxiliary auxiliary = new Auxiliary();
            auxiliary.setId(d.getId());
            auxiliary.setUpdateTime(new Date());
            auxiliary.setNum(d.getNum());
            auxiliaryMapper.updateAuxiliaryNum(auxiliary);
        });
    }

    /** 修改工单管理 */
    @Transactional
    @Override
    public AjaxResult updateStoreOrder(StoreOrder storeOrder) {
        if(storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 2L){
            return updateOrderByCargo(storeOrder);
        }else if(storeOrder.getOrderType() == 3L || storeOrder.getOrderType() == 4L){
            return updateOrderByAuxiliary(storeOrder);
        }
        return AjaxResult.error("工单类型错误");
    }
    public AjaxResult updateOrderByCargo(StoreOrder storeOrder) {
        try {
            //校验及修改项目工单货物未入库数量
            StoreOrderCargo storeOrderCargo = new StoreOrderCargo();
            storeOrderCargo.setOrderId(storeOrder.getOrderId());
            List<StoreOrderCargo> storeOrderCargoListOld = storeOrderCargoMapper.getCargoListByNum(storeOrderCargo);
            Map<String, StoreOrderCargo> projectCargoMap = storeOrderCargoListOld.stream().collect(Collectors.toMap(StoreOrderCargo::getCargoName, Function.identity()));
            List<StoreOrderCargo> storeOrderCargoList = storeOrder.getStoreOrderCargoList();
            //函数式写法
            Function<StoreOrderCargo, Long> cargoNumSelector = storeOrder.getOrderType() == 1L ? StoreOrderCargo::getCargoInputNum : StoreOrderCargo::getCargoOutNum;
            List<String> diffList = storeOrderCargoList.stream().filter(d -> {
                StoreOrderCargo cargo = projectCargoMap.get(d.getCargoName());
                return d.getCargoNum() != null && d.getCargoNum() > (cargo.getCargoNum() + cargoNumSelector.apply(cargo));
            }).map(StoreOrderCargo::getCargoName).collect(Collectors.toList());
            if (diffList != null && diffList.size() > 0) {
                return AjaxResult.error(storeOrder.getOrderType() == 1L ? "未入库数量已变更，请刷新页面" : "未出库数量已变更，请刷新页面");
            }
            storeOrder.setUpdateTime(DateUtils.getNowDate());
            updateCargo(storeOrder);
            storeOrderMapper.updateStoreOrder(storeOrder);
        } catch (Exception e) {
            log.error("修改工单失败|{}", e);
            throw new RuntimeException("修改工单失败", e);
        }
        return AjaxResult.success();
    }
    public AjaxResult updateOrderByAuxiliary(StoreOrder storeOrder) {
        try {
            storeOrder.setUpdateTime(DateUtils.getNowDate());
            storeOrderAuxiliaryMapper.deleteStoreOrderAuxiliaryByOrderId(storeOrder.getOrderId());
            insertStoreOrderAuxiliary(storeOrder);
            storeOrderMapper.updateStoreOrder(storeOrder);
        } catch (Exception e) {
            log.error("修改工单失败|{}", e);
            throw new RuntimeException("修改工单失败", e);
        }
        return AjaxResult.success();
    }

    /** 批量删除工单管理 */
    @Transactional
    @Override
    public int deleteStoreOrderByOrderIds(Long[] orderIds) {
        storeOrderCargoMapper.deleteStoreOrderCargoByOrderIds(orderIds);
        storeOrderAuxiliaryMapper.deleteStoreOrderAuxiliaryByOrderIds(orderIds);
        return storeOrderMapper.deleteStoreOrderByOrderIds(orderIds);
    }

    /** 删除工单管理信息 */
    @Transactional
    @Override
    public int deleteStoreOrderByOrderId(Long orderId) {
        storeOrderCargoMapper.deleteStoreOrderCargoByOrderId(orderId);
        storeOrderAuxiliaryMapper.deleteStoreOrderAuxiliaryByOrderId(orderId);
        return storeOrderMapper.deleteStoreOrderByOrderId(orderId);
    }

    /** 修改工单状态 */
    @Transactional
    @Override
    public AjaxResult updateStatus(StoreOrder storeOrder) {
        try {
            storeOrder.setUpdateTime(DateUtils.getNowDate());
            /**
             * 货物入库工单orderType=1 or 货物出库工单orderType=2 or 辅料入库工单orderType=3 or 辅料出库工单orderType=4
             * 货运方式-公司车辆transportType=1
             * 待领取->待出发
             * 待领取->待验货
             */
            if ("0".equals(storeOrder.getOrderStatus())) {
                if(storeOrder.getTransportType() == 1L){
                    //更新车辆状态
                    updateCarStatus(storeOrder);
                    //待出发
                    storeOrder.setOrderStatus("1");
                    storeOrder.setTakeCarTime(DateUtils.getNowDate());
                }else {
                    //待验货
                    storeOrder.setOrderStatus("3");
                }
            }
            /**
             * 货物入库工单orderType=1 or 货物出库工单orderType=2 or 辅料入库工单orderType=3 or 辅料出库工单orderType=4
             * 货运方式-公司车辆transportType=1
             * 待出发->已出发
             */
            else if (storeOrder.getTransportType() == 1L && "1".equals(storeOrder.getOrderStatus())) {
                //已出发
                storeOrder.setOrderStatus("2");
                storeOrder.setDepartTime(DateUtils.getNowDate());
            }
            /**
             * 货物入库工单orderType=1 or 货物出库工单orderType=2 or 辅料入库工单orderType=3 or 辅料出库工单orderType=4
             * 货运方式-公司车辆transportType=1
             * 已出发->待验货
             */
            else if (storeOrder.getTransportType() == 1L && "2".equals(storeOrder.getOrderStatus())) {
                //待验货
                storeOrder.setOrderStatus("3");
                storeOrder.setArriveTime(DateUtils.getNowDate());
            }
            /**
             * 货物入库工单orderType=1 or 货物出库工单orderType=2 or 辅料入库工单orderType=3 or 辅料出库工单orderType=4
             * 待验货->已验货
             * 待验货->已到厂
             * 待验货->已完成
             */
            else if ("3".equals(storeOrder.getOrderStatus())) {
                if((storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 2L)){
                    //更新货物数量
                    updateCargo(storeOrder);
                }
                //插入货物图片
                insertImage(storeOrder.getImageCargo(), storeOrder.getOrderId(), "1");
                //插入单据图片
                insertImage(storeOrder.getImageOrder(), storeOrder.getOrderId(), "3");
                if (storeOrder.getTransportType() == 1L) {
                    //已验货
                    storeOrder.setOrderStatus("4");
                } else {
                    if (storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 3L) {
                        //已到厂
                        storeOrder.setOrderStatus("7");
                        storeOrder.setBackStoreTime(DateUtils.getNowDate());
                    }else if (storeOrder.getOrderType() == 2L || storeOrder.getOrderType() == 4L) {
                        //已完成
                        storeOrder.setOrderStatus("9");
                        storeOrder.setOrderWholeStatus("1");
                    }
                }
            }
            /**
             * 货物入库工单orderType=1 or 货物出库工单orderType=2 or 辅料入库工单orderType=3 or 辅料出库工单orderType=4
             * 货运方式-公司车辆transportType=1
             * 已验货->待返程
             */
            else if (storeOrder.getTransportType() == 1L && "4".equals(storeOrder.getOrderStatus())) {
                //待返程
                storeOrder.setOrderStatus("5");
            }
            /**
             * 入库工单orderType=1 or 出库工单orderType=2
             * 货运方式-公司车辆transportType=1
             * 待返程->已返程
             */
            else if (storeOrder.getTransportType() == 1L && "5".equals(storeOrder.getOrderStatus())) {
                //已返程
                storeOrder.setOrderStatus("6");
                storeOrder.setBackTime(DateUtils.getNowDate());
            }
            /**
             * 货物入库工单orderType=1 or 货物出库工单orderType=2 or 辅料入库工单orderType=3 or 辅料出库工单orderType=4
             * 货运方式-公司车辆transportType=1
             * 已返程->已到厂
             * 已返程->已完成
             */
            else if ("6".equals(storeOrder.getOrderStatus())) {
                if(storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 3L){
                    //已到厂
                    storeOrder.setOrderStatus("7");
                    storeOrder.setBackStoreTime(DateUtils.getNowDate());
                }else if(storeOrder.getOrderType() == 2L || storeOrder.getOrderType() == 4L){
                    //释放车辆
                    updateCarStatus(storeOrder);
                    //插入车辆图片
                    insertImage(storeOrder.getImageCar(), storeOrder.getOrderId(), "2");
                    //已完成
                    storeOrder.setOrderStatus("9");
                    storeOrder.setOrderWholeStatus("1");
                    storeOrder.setReturnCarTime(DateUtils.getNowDate());
                }
            }
            /**
             * 入库工单orderType=1 or 辅料入库工单orderType=3
             * 已到厂->已入库
             */
            else if ((storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 3L) && "7".equals(storeOrder.getOrderStatus())) {
                if(storeOrder.getOrderType() == 1L){
                    //入库操作
                    if (inputCargo(storeOrder)) {
                        return AjaxResult.error("数量不正确");
                    }
                }else{
                    inputAuxiliary(storeOrder);
                }
                //已入库
                storeOrder.setOrderStatus("8");
                storeOrder.setInputStoreTime(DateUtils.getNowDate());
            }
            /**
             * 入库工单orderType=1 or 辅料入库工单orderType=3
             * 已入库->已完成
             */
            else if ((storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 3L) && "8".equals(storeOrder.getOrderStatus())) {
                if (storeOrder.getTransportType() == 1L) {
                    //插入车辆图片
                    insertImage(storeOrder.getImageCar(), storeOrder.getOrderId(), "2");
                    //释放车辆
                    updateCarStatus(storeOrder);
                    //已完成
                    storeOrder.setReturnCarTime(DateUtils.getNowDate());
                }
                storeOrder.setOrderStatus("9");
                storeOrder.setOrderWholeStatus("1");
            }
            storeOrderMapper.updateStoreOrder(storeOrder);
            //判断项目状态
            if (storeOrder.getOrderType() == 1L && "9".equals(storeOrder.getOrderStatus()) && storeOrderMapper.checkProjectStatus(storeOrder.getProjectId()) == 0) {
                Project project = new Project();
                project.setProjectId(storeOrder.getProjectId().intValue());
                project.setProjectStatus(1L);
                project.setUpdateTime(DateUtils.getNowDate());
                projectMapper.updateProject(project);
            }
        } catch (Exception e) {
            log.error("修改工单状态失败|{}", e);
            throw new RuntimeException("修改工单状态失败", e);
        }
        return AjaxResult.success();
    }

    /** 货物入库操作 */
    private Boolean inputCargo(StoreOrder storeOrder) {
        //校验数量
        StoreOrderCargo storeOrderCargo = new StoreOrderCargo();
        storeOrderCargo.setOrderId(storeOrder.getOrderId());
        List<StoreOrderCargo> storeOrderCargoListOld = storeOrderCargoMapper.selectStoreOrderCargoList(storeOrderCargo);
        Map<String, Long> cargoMap = storeOrderCargoListOld.stream().collect(Collectors.toMap(StoreOrderCargo::getCargoName, StoreOrderCargo::getCargoNum));
        List<StoreOrderCargo> storeOrderCargoList = storeOrder.getStoreOrderCargoList();
        List<String> diffList = storeOrderCargoList.stream().filter(d -> {
            Long num = cargoMap.get(d.getCargoName());
            return d.getCargoNum() == null || d.getCargoNum().compareTo(num) != 0;
        }).map(StoreOrderCargo::getCargoName).collect(Collectors.toList());
        if (diffList != null && diffList.size() > 0) {
            return true;
        }
        //项目入库
        storeOrderCargoList.stream().filter(f -> Objects.nonNull(f.getCargoNum()) && f.getCargoNum() > 0).forEach(d -> {
            ProjectCargo projectCargo = new ProjectCargo();
            projectCargo.setProjectId(storeOrder.getProjectId().intValue());
            projectCargo.setCargoOutNum(d.getCargoNum().intValue());
            projectCargo.setCargoName(d.getCargoName());
            projectExtendMapper.updateOutNumByInput(projectCargo);
        });
        return false;
    }

    /** 辅料入库操作 */
    private void inputAuxiliary(StoreOrder storeOrder) {
        StoreOrderAuxiliary storeOrderAuxiliary = new StoreOrderAuxiliary();
        storeOrderAuxiliary.setOrderId(storeOrder.getOrderId());
        List<StoreOrderAuxiliary> auxiliaryList = storeOrderAuxiliaryMapper.selectStoreOrderAuxiliaryList(storeOrderAuxiliary);
        auxiliaryList.stream().forEach(d -> {
            Auxiliary auxiliary = new Auxiliary();
            auxiliary.setAuxiliaryType(d.getAuxiliaryType());
            auxiliary.setName(d.getName());
            auxiliary.setSpecifications(d.getSpecifications());
            auxiliary.setUnit(d.getUnit());
            auxiliary.setModel(d.getModel());
            Auxiliary auxiliarySelect = auxiliaryMapper.selectAuxiliary(auxiliary);
            if(auxiliarySelect == null){
                auxiliary.setNum(d.getNum());
                auxiliary.setStatus("1");
                auxiliary.setCreateTime(new Date());
                auxiliary.setUpdateTime(new Date());
                auxiliaryMapper.insertAuxiliary(auxiliary);
            }else{
                auxiliarySelect.setNum(d.getNum() + auxiliarySelect.getNum());
                auxiliarySelect.setUpdateTime(new Date());
                auxiliaryMapper.updateAuxiliary(auxiliarySelect);
            }
        });
    }

    /** 插入图片 */
    private void insertImage(String image, Long orderId, String type) {
        if (StringUtils.isNotNull(image)) {
            List<Images> imagesList = new ArrayList<>();
            Arrays.asList(image.split(",")).stream().forEach(d -> {
                Images images = new Images();
                images.setSourceId(orderId);
                images.setImageType(type);
                images.setFilePath(d);
                images.setCreateTime(DateUtils.getNowDate());
                images.setUpdateTime(DateUtils.getNowDate());
                imagesList.add(images);
            });
            imagesMapper.batchImage(imagesList);
        }
    }

    /** 更新车辆状态 */
    private void updateCarStatus(StoreOrder storeOrder) {
        Car car = new Car();
        if (storeOrder.getReturnCarDistance() != null) {
            //释放车辆
            car.setCarId(Long.valueOf(storeOrder.getFactLicensePlate()));
            car.setUpdateTime(DateUtils.getNowDate());
            car.setCarKilometers(storeOrder.getReturnCarDistance());
            car.setCarStatus("0");
        } else {
            //更新车辆状态
            car = carMapper.selectCarByCarId(Long.valueOf(storeOrder.getFactLicensePlate()));
            car.setUpdateTime(DateUtils.getNowDate());
            car.setCarStatus("1");
            storeOrder.setTakeCarDistance(car.getCarKilometers());
        }
        carMapper.updateCar(car);
    }

    /** 更新货物数量（货物数量变化的情况下） */
    private void updateCargo(StoreOrder storeOrder) {
        StoreOrderCargo storeOrderCargo = new StoreOrderCargo();
        storeOrderCargo.setOrderId(storeOrder.getOrderId());
        List<StoreOrderCargo> storeOrderCargoListOld = storeOrderCargoMapper.selectStoreOrderCargoList(storeOrderCargo);
        Map<String, Long> cargoMap = storeOrderCargoListOld.stream().collect(Collectors.toMap(StoreOrderCargo::getCargoName, StoreOrderCargo::getCargoNum));
        List<StoreOrderCargo> storeOrderCargoList = storeOrder.getStoreOrderCargoList();
        List<StoreOrderCargo> diffList = new ArrayList<>();
        storeOrderCargoList.stream().forEach(d -> {
            Long num = cargoMap.get(d.getCargoName());
            if (d.getCargoNum() == null && num != 0L) {
                d.setCargoNum(0L);
                d.setCargoNumDiff(num);
                diffList.add(d);
            } else if (d.getCargoNum() != null && d.getCargoNum().compareTo(num) != 0) {
                d.setCargoNumDiff(num - d.getCargoNum());
                diffList.add(d);
            }
        });
        if (diffList.size() > 0) {
            diffList.stream().forEach(d -> {
                storeOrderCargoMapper.updateStoreOrderCargo(d);
                ProjectCargo projectCargo = new ProjectCargo();
                projectCargo.setProjectId(storeOrder.getProjectId().intValue());
                projectCargo.setCargoName(d.getCargoName());
                projectCargo.setCargoNumDiff(d.getCargoNumDiff());
                //函数式写法
                Consumer<ProjectCargo> updateMethod = storeOrder.getOrderType() == 1L ? projectExtendMapper::updateInputNumByDiff : projectExtendMapper::updateOutNumByDiff;
                updateMethod.accept(projectCargo);
            });
        }
    }

    /** 查询工单管理 */
    @Override
    public StoreOrder getOrderDetail(StoreOrder storeOrder) {
        if(storeOrder.getOrderType() == 1L || storeOrder.getOrderType() == 2L){
            return getOrderDetailByCargo(storeOrder.getOrderId());
        }else if(storeOrder.getOrderType() == 3L || storeOrder.getOrderType() == 4L){
            return getOrderDetailByAuxiliary(storeOrder.getOrderId());
        }
        return null;
    }
    public StoreOrder getOrderDetailByCargo(Long orderId) {
        StoreOrder orderDetail = storeOrderMapper.getOrderDetailByCargo(orderId);
        if (orderDetail != null) {
            StoreOrderCargo storeOrderCargo = new StoreOrderCargo();
            storeOrderCargo.setOrderId(orderId);
            List<StoreOrderCargo> storeOrderCargoList = storeOrderCargoMapper.selectCargoListNotZero(storeOrderCargo);
            orderDetail.setStoreOrderCargoList(storeOrderCargoList);
            getImage(orderDetail);
        }
        return orderDetail;
    }
    public StoreOrder getOrderDetailByAuxiliary(Long orderId) {
        StoreOrder orderDetail = storeOrderMapper.getOrderDetailByAuxiliary(orderId);
        if (orderDetail != null) {
            StoreOrderAuxiliary storeOrderAuxiliary = new StoreOrderAuxiliary();
            storeOrderAuxiliary.setOrderId(orderId);
            List<StoreOrderAuxiliary> storeOrderAuxiliaryList = storeOrderAuxiliaryMapper.selectStoreOrderAuxiliaryList(storeOrderAuxiliary);
            orderDetail.setStoreOrderAuxiliaryList(storeOrderAuxiliaryList);
            getImage(orderDetail);
        }
        return orderDetail;
    }

    /** 获取图片 1 货物 2 车辆 3 单据 */
    public void getImage(StoreOrder orderDetail){
        Images images = new Images();
        images.setSourceId(orderDetail.getOrderId());
        List<Images> imagesList = imagesMapper.selectImagesList(images);
        if (imagesList != null && imagesList.size() > 0) {
            Map<String, List<Images>> typeMap = imagesList.stream().collect(Collectors.groupingBy(Images::getImageType));
            if (typeMap.get("1") != null && typeMap.get("1").size() > 0) {
                orderDetail.setImageCargo(typeMap.get("1").stream().map(image -> image.getFilePath()).collect(Collectors.joining(",")));
            }
            if (typeMap.get("2") != null && typeMap.get("2").size() > 0) {
                orderDetail.setImageCar(typeMap.get("2").stream().map(image -> image.getFilePath()).collect(Collectors.joining(",")));
            }
            if (typeMap.get("3") != null && typeMap.get("3").size() > 0) {
                orderDetail.setImageOrder(typeMap.get("3").stream().map(image -> image.getFilePath()).collect(Collectors.joining(",")));
            }
        }
    }

    /** 查询待办任务列表 */
    @Override
    public List<StoreOrder> getTodoList(StoreOrder storeOrder) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        User userInfo = userMapper.getUserInfo(userId);
        storeOrder.setUserId(userId);
        if(userInfo.getRoleKeys() != null ){
            if(userInfo.getRoleKeys().contains("admin") || userInfo.getRoleKeys().contains("superAdmin")){
                return storeOrderMapper.selectStoreOrderList(storeOrder);
            }else if(userInfo.getRoleKeys().contains("manager")){
                //管理角色
                return storeOrderMapper.selectTodoListByManager(storeOrder);
            }
        }
        if(userInfo.getPostCodes() != null ){
            if(userInfo.getPostCodes().contains("driver")){
                //司机
                return storeOrderMapper.selectTodoListByDriver(storeOrder);
            }else if(userInfo.getPostCodes().contains("kg")){
                //库管
                return storeOrderMapper.selectTodoListByKg(storeOrder);
            }
        }
        return null;
    }
}